import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../constants/constants.dart';

import 'player_screen.dart';

/// 音乐列表页面
/// 显示音乐库中的所有音乐，支持搜索、排序和播放
class MusicListScreen extends StatefulWidget {
  const MusicListScreen({super.key});

  @override
  State<MusicListScreen> createState() => _MusicListScreenState();
}

class _MusicListScreenState extends State<MusicListScreen>
    with TickerProviderStateMixin {
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;

  List<Music> _musicList = [];
  List<Music> _filteredMusicList = [];
  bool _isLoading = true;
  String _searchQuery = '';
  SortType _sortType = SortType.title;
  bool _isAscending = true;

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _loadMusicList();
    _searchController.addListener(_onSearchChanged);
  }

  /// 初始化动画
  void _initAnimations() {
    _fadeController = AnimationController(
      duration: AppTheme.animationDurationMedium,
      vsync: this,
    );
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeInOut,
    ));
  }

  /// 加载音乐列表
  Future<void> _loadMusicList() async {
    try {
      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);
      final musicList = await musicLibraryService.getAllMusic();

      setState(() {
        _musicList = musicList;
        _filteredMusicList = musicList;
        _isLoading = false;
      });

      _fadeController.forward();
      _applySorting();
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showErrorSnackBar('加载音乐列表失败: $e');
    }
  }

  /// 搜索变化处理
  void _onSearchChanged() {
    setState(() {
      _searchQuery = _searchController.text;
      _filterMusicList();
    });
  }

  /// 过滤音乐列表
  void _filterMusicList() {
    if (_searchQuery.isEmpty) {
      _filteredMusicList = List.from(_musicList);
    } else {
      _filteredMusicList = _musicList.where((music) {
        return music.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
            music.artist.toLowerCase().contains(_searchQuery.toLowerCase()) ||
            (music.album?.toLowerCase().contains(_searchQuery.toLowerCase()) ??
                false);
      }).toList();
    }
    _applySorting();
  }

  /// 应用排序
  void _applySorting() {
    _filteredMusicList.sort((a, b) {
      int comparison;
      switch (_sortType) {
        case SortType.title:
          comparison = a.title.compareTo(b.title);
          break;
        case SortType.artist:
          comparison = a.artist.compareTo(b.artist);
          break;
        case SortType.album:
          comparison = (a.album ?? '').compareTo(b.album ?? '');
          break;
        case SortType.duration:
          comparison = a.duration.compareTo(b.duration);
          break;
        case SortType.dateAdded:
          comparison = a.createdAt.compareTo(b.createdAt);
          break;
      }
      return _isAscending ? comparison : -comparison;
    });
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.errorColor,
      ),
    );
  }

  /// 显示排序选项
  void _showSortOptions() {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.surfaceDark,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(AppTheme.radiusLarge),
        ),
      ),
      builder: (context) => _buildSortBottomSheet(),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.dispose();
    _fadeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: AppTheme.backgroundGradientDark,
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部搜索栏
              _buildSearchHeader(),

              // 音乐列表
              Expanded(
                child: _isLoading
                    ? _buildLoadingState()
                    : _filteredMusicList.isEmpty
                        ? _buildEmptyState()
                        : _buildMusicList(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建搜索头部
  Widget _buildSearchHeader() {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingMedium),
      child: Column(
        children: [
          // 标题和排序按钮
          Row(
            children: [
              const Expanded(
                child: Text(
                  '音乐库',
                  style: TextStyle(
                    fontSize: AppTheme.fontSizeXL,
                    fontWeight: FontWeight.bold,
                    color: AppTheme.textPrimaryDark,
                  ),
                ),
              ),
              IconButton(
                onPressed: _showSortOptions,
                icon: const Icon(
                  Icons.sort,
                  color: AppTheme.textPrimaryDark,
                  size: AppTheme.iconSizeLarge,
                ),
              ),
            ],
          ),

          const SizedBox(height: AppTheme.spacingMedium),

          // 搜索框
          Container(
            decoration: BoxDecoration(
              color: AppTheme.surfaceDark,
              borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
              border: Border.all(
                color: AppTheme.primaryColor.withOpacity(0.3),
                width: 1,
              ),
            ),
            child: TextField(
              controller: _searchController,
              style: const TextStyle(color: AppTheme.textPrimaryDark),
              decoration: const InputDecoration(
                hintText: '搜索音乐、艺术家或专辑...',
                hintStyle: TextStyle(color: AppTheme.textHintDark),
                prefixIcon: Icon(
                  Icons.search,
                  color: AppTheme.textSecondaryDark,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: AppTheme.spacingMedium,
                  vertical: AppTheme.spacingSmall,
                ),
              ),
            ),
          ),

          // 结果统计
          if (!_isLoading) ...[
            const SizedBox(height: AppTheme.spacingSmall),
            Row(
              children: [
                Text(
                  '共 ${_filteredMusicList.length} 首音乐',
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeSmall,
                    color: AppTheme.textSecondaryDark,
                  ),
                ),
                if (_searchQuery.isNotEmpty) ...[
                  const Text(
                    ' • ',
                    style: TextStyle(
                      fontSize: AppTheme.fontSizeSmall,
                      color: AppTheme.textSecondaryDark,
                    ),
                  ),
                  Text(
                    '搜索: "$_searchQuery"',
                    style: const TextStyle(
                      fontSize: AppTheme.fontSizeSmall,
                      color: AppTheme.primaryColor,
                    ),
                  ),
                ],
              ],
            ),
          ],
        ],
      ),
    );
  }

  /// 构建加载状态
  Widget _buildLoadingState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
          ),
          SizedBox(height: AppTheme.spacingMedium),
          Text(
            '正在加载音乐库...',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textSecondaryDark,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: AppTheme.albumCoverSizeLarge,
            height: AppTheme.albumCoverSizeLarge,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: AppTheme.surfaceDark,
              border: Border.all(
                color: AppTheme.primaryColor.withOpacity(0.3),
                width: 2,
              ),
            ),
            child: const Icon(
              Icons.library_music,
              size: AppTheme.iconSizeXL,
              color: AppTheme.textHintDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingLarge),
          Text(
            _searchQuery.isEmpty ? '音乐库为空' : '未找到匹配的音乐',
            style: const TextStyle(
              fontSize: AppTheme.fontSizeLarge,
              color: AppTheme.textSecondaryDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          Text(
            _searchQuery.isEmpty ? '扫描本地音乐文件来添加音乐' : '尝试使用不同的关键词搜索',
            style: const TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textHintDark,
            ),
            textAlign: TextAlign.center,
          ),
          if (_searchQuery.isEmpty) ...[
            const SizedBox(height: AppTheme.spacingXL),
            ElevatedButton(
              onPressed: () {
                // TODO: 实现音乐扫描功能
              },
              child: const Text('扫描音乐'),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建音乐列表
  Widget _buildMusicList() {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: ListView.builder(
        controller: _scrollController,
        padding: const EdgeInsets.symmetric(
          horizontal: AppTheme.spacingMedium,
        ),
        itemCount: _filteredMusicList.length,
        itemBuilder: (context, index) {
          final music = _filteredMusicList[index];
          return _buildMusicItem(music, index);
        },
      ),
    );
  }

  /// 构建音乐项
  Widget _buildMusicItem(Music music, int index) {
    return Consumer<AudioPlayerService>(
      builder: (context, audioService, child) {
        final isCurrentMusic = audioService.currentMusic?.id == music.id;
        final isPlaying = isCurrentMusic && audioService.isPlaying;

        return Container(
          margin: const EdgeInsets.only(bottom: AppTheme.spacingSmall),
          decoration: BoxDecoration(
            color: isCurrentMusic
                ? AppTheme.primaryColor.withOpacity(0.1)
                : AppTheme.surfaceDark,
            borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
            border: isCurrentMusic
                ? Border.all(
                    color: AppTheme.primaryColor.withOpacity(0.5),
                    width: 1,
                  )
                : null,
          ),
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(
              horizontal: AppTheme.spacingMedium,
              vertical: AppTheme.spacingSmall,
            ),
            leading: _buildMusicCover(music, isPlaying),
            title: Text(
              music.title,
              style: TextStyle(
                fontSize: AppTheme.fontSizeMedium,
                fontWeight:
                    isCurrentMusic ? FontWeight.w600 : FontWeight.normal,
                color: isCurrentMusic
                    ? AppTheme.primaryColor
                    : AppTheme.textPrimaryDark,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  music.artist,
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeSmall,
                    color: AppTheme.textSecondaryDark,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                if (music.album != null) ...[
                  const SizedBox(height: 2),
                  Text(
                    music.album!,
                    style: const TextStyle(
                      fontSize: AppTheme.fontSizeXS,
                      color: AppTheme.textHintDark,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ],
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  music.formattedDuration,
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeSmall,
                    color: AppTheme.textSecondaryDark,
                  ),
                ),
                const SizedBox(width: AppTheme.spacingSmall),
                IconButton(
                  onPressed: () => _showMusicOptions(music),
                  icon: const Icon(
                    Icons.more_vert,
                    color: AppTheme.textSecondaryDark,
                    size: AppTheme.iconSizeMedium,
                  ),
                ),
              ],
            ),
            onTap: () => _playMusic(music, index),
          ),
        );
      },
    );
  }

  /// 构建音乐封面
  Widget _buildMusicCover(Music music, bool isPlaying) {
    return Container(
      width: AppTheme.albumCoverSizeMedium,
      height: AppTheme.albumCoverSizeMedium,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
        gradient: AppTheme.primaryGradient,
      ),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
            child: music.coverArt != null
                ? Image.asset(
                    music.coverArt!,
                    width: AppTheme.albumCoverSizeMedium,
                    height: AppTheme.albumCoverSizeMedium,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return _buildDefaultMusicCover();
                    },
                  )
                : _buildDefaultMusicCover(),
          ),
          if (isPlaying)
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
                color: Colors.black.withOpacity(0.5),
              ),
              child: const Center(
                child: Icon(
                  Icons.equalizer,
                  color: AppTheme.primaryColor,
                  size: AppTheme.iconSizeMedium,
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建默认音乐封面
  Widget _buildDefaultMusicCover() {
    return Container(
      width: AppTheme.albumCoverSizeMedium,
      height: AppTheme.albumCoverSizeMedium,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
        gradient: AppTheme.primaryGradient,
      ),
      child: const Icon(
        Icons.music_note,
        color: Colors.white,
        size: AppTheme.iconSizeMedium,
      ),
    );
  }

  /// 播放音乐
  void _playMusic(Music music, int index) {
    final audioService =
        Provider.of<AudioPlayerService>(context, listen: false);

    // 设置播放列表并播放指定音乐
    audioService.playMusic(music, playlist: _filteredMusicList, index: index);

    // 导航到播放页面
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const PlayerScreen(),
      ),
    );
  }

  /// 显示音乐选项
  void _showMusicOptions(Music music) {
    showModalBottomSheet(
      context: context,
      backgroundColor: AppTheme.surfaceDark,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(AppTheme.radiusLarge),
        ),
      ),
      builder: (context) => _buildMusicOptionsBottomSheet(music),
    );
  }

  /// 构建音乐选项底部表单
  Widget _buildMusicOptionsBottomSheet(Music music) {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingMedium),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 音乐信息
          ListTile(
            leading: _buildMusicCover(music, false),
            title: Text(
              music.title,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeMedium,
                fontWeight: FontWeight.w600,
                color: AppTheme.textPrimaryDark,
              ),
            ),
            subtitle: Text(
              music.artist,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textSecondaryDark,
              ),
            ),
          ),

          const Divider(color: AppTheme.dividerDark),

          // 选项列表
          ListTile(
            leading: const Icon(
              Icons.play_arrow,
              color: AppTheme.primaryColor,
            ),
            title: const Text(
              '播放',
              style: TextStyle(color: AppTheme.textPrimaryDark),
            ),
            onTap: () {
              Navigator.of(context).pop();
              _playMusic(music, _filteredMusicList.indexOf(music));
            },
          ),
          ListTile(
            leading: const Icon(
              Icons.playlist_add,
              color: AppTheme.textSecondaryDark,
            ),
            title: const Text(
              '添加到播放列表',
              style: TextStyle(color: AppTheme.textPrimaryDark),
            ),
            onTap: () {
              Navigator.of(context).pop();
              // TODO: 实现添加到播放列表功能
            },
          ),
          ListTile(
            leading: Icon(
              music.isFavorite ? Icons.favorite : Icons.favorite_border,
              color: music.isFavorite
                  ? AppTheme.errorColor
                  : AppTheme.textSecondaryDark,
            ),
            title: Text(
              music.isFavorite ? '取消收藏' : '收藏',
              style: const TextStyle(color: AppTheme.textPrimaryDark),
            ),
            onTap: () {
              Navigator.of(context).pop();
              _toggleFavorite(music);
            },
          ),
          ListTile(
            leading: const Icon(
              Icons.info_outline,
              color: AppTheme.textSecondaryDark,
            ),
            title: const Text(
              '音乐信息',
              style: TextStyle(color: AppTheme.textPrimaryDark),
            ),
            onTap: () {
              Navigator.of(context).pop();
              _showMusicInfo(music);
            },
          ),
        ],
      ),
    );
  }

  /// 构建排序底部表单
  Widget _buildSortBottomSheet() {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingMedium),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '排序方式',
            style: TextStyle(
              fontSize: AppTheme.fontSizeLarge,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingMedium),

          // 排序选项
          ...SortType.values.map((sortType) {
            return ListTile(
              leading: Icon(
                _getSortIcon(sortType),
                color: _sortType == sortType
                    ? AppTheme.primaryColor
                    : AppTheme.textSecondaryDark,
              ),
              title: Text(
                _getSortTitle(sortType),
                style: TextStyle(
                  color: _sortType == sortType
                      ? AppTheme.primaryColor
                      : AppTheme.textPrimaryDark,
                  fontWeight: _sortType == sortType
                      ? FontWeight.w600
                      : FontWeight.normal,
                ),
              ),
              trailing: _sortType == sortType
                  ? Icon(
                      _isAscending ? Icons.arrow_upward : Icons.arrow_downward,
                      color: AppTheme.primaryColor,
                    )
                  : null,
              onTap: () {
                setState(() {
                  if (_sortType == sortType) {
                    _isAscending = !_isAscending;
                  } else {
                    _sortType = sortType;
                    _isAscending = true;
                  }
                  _applySorting();
                });
                Navigator.of(context).pop();
              },
            );
          }),
        ],
      ),
    );
  }

  /// 获取排序图标
  IconData _getSortIcon(SortType sortType) {
    switch (sortType) {
      case SortType.title:
        return Icons.title;
      case SortType.artist:
        return Icons.person;
      case SortType.album:
        return Icons.album;
      case SortType.duration:
        return Icons.access_time;
      case SortType.dateAdded:
        return Icons.date_range;
    }
  }

  /// 获取排序标题
  String _getSortTitle(SortType sortType) {
    switch (sortType) {
      case SortType.title:
        return '标题';
      case SortType.artist:
        return '艺术家';
      case SortType.album:
        return '专辑';
      case SortType.duration:
        return '时长';
      case SortType.dateAdded:
        return '添加日期';
    }
  }

  /// 切换收藏状态
  void _toggleFavorite(Music music) async {
    try {
      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);
      await musicLibraryService.toggleFavorite(music);

      // 更新本地列表
      setState(() {
        final index = _musicList.indexWhere((m) => m.id == music.id);
        if (index != -1) {
          _musicList[index] = _musicList[index].copyWith(
            isFavorite: !_musicList[index].isFavorite,
          );
        }
        _filterMusicList();
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              music.isFavorite ? '已取消收藏' : '已添加到收藏',
            ),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('操作失败: $e');
      }
    }
  }

  /// 显示音乐信息
  void _showMusicInfo(Music music) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: AppTheme.surfaceDark,
        title: const Text(
          '音乐信息',
          style: TextStyle(color: AppTheme.textPrimaryDark),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildInfoRow('标题', music.title),
            _buildInfoRow('艺术家', music.artist),
            if (music.album != null) _buildInfoRow('专辑', music.album!),
            _buildInfoRow('时长', music.formattedDuration),
            _buildInfoRow('文件大小', music.formattedFileSize),
            _buildInfoRow('文件路径', music.filePath),
            _buildInfoRow('添加日期', music.createdAt.toString().split(' ')[0]),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text(
              '关闭',
              style: TextStyle(color: AppTheme.primaryColor),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textSecondaryDark,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall,
                color: AppTheme.textPrimaryDark,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// 排序类型枚举
enum SortType {
  title,
  artist,
  album,
  duration,
  dateAdded,
}
